package com.roy.sms.dao;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;

import com.roy.sms.model.Column;
import com.roy.sms.model.Role;
import com.roy.sms.model.User;

@Repository
public class RoleDao {

	@Resource
	private SessionFactory sessionFactory;
	
	private Session getSession(){
		return sessionFactory.getCurrentSession();
	}
	
	public Role add(Role role){
		getSession().save(role);
		return role;
	}
	
	public Role load(int id){
		return (Role) getSession().load(Role.class, id);
	}
	
	public void delete(int id){
		getSession().delete(load(id));
	}
	
	public void update(Role role){
		getSession().update(role);
	}
	
	@SuppressWarnings("unchecked")
	public List<Role> list(){
		return getSession().createQuery("from Role").list();
	}
	
	@SuppressWarnings("unchecked")
	public List<Column> queryUserColumn(User u){
		String hql = "select r.columns from Role r join r.users u where u=?";
		return getSession().createQuery(hql).setParameter(0, u).list();
	}
	
}
